﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Diagnostics;

using ShootSearch.Core;
using ShootSearch.Core.ObjectItems;

namespace ShootSearch.Indexers
{
    public class DBIndexer: IIndexer
    {

        protected DBIndexerConfig config;
        protected DbCommand dbCommand;
        protected IObjectParser objParser;

        public DbConnection DbConnection { get; protected set; }

        #region IIndexer Members

        public bool Create()
        {
            bool result = true;

            if (config!=null)
            {
                objParser = config.ObjectParser.GetObjectWithConfig() as IObjectParser;
                if (objParser == null)
                {
                    result = false;
                }
                else
                {

                    try
                    {
                        DbConnection = (DbConnection)config.Connection.GetObject();
                        DbConnection.ConnectionString = config.ConnectionString;
                        DbConnection.Open();
                        dbCommand = DbConnection.CreateCommand();
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                        result = false;
                    }
                }          

            }
            else result = false;

            return result;
        }


        public bool Add(object doc)
        {
            bool parsed = objParser.Parse(doc, ref dbCommand);

            if (parsed)
            {
                try
                {
                    parsed = dbCommand.ExecuteNonQuery() > 0;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex);
                    parsed = false;
                }
                
            }

            return parsed;
        }

        public void Close()
        {
            if (DbConnection != null
                && DbConnection.State == ConnectionState.Open)
            {
                try
                {
                    DbConnection.Close();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex);
                }
            }
        }

        #endregion

        #region IConfigable Members

        public ShootSearch.Core.SpiderManConfig Config
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion

        
    }
}
